/**
 * ajax请求配置
 */
import axios from 'axios'
import dsktConstant from './constant.js'

import { AlertModule } from 'vux'

//import Qs from 'qs'


import cookie from '../assets/js/cookie.js'

// axios默认配置
axios.defaults.timeout = 10000;   // 超时时间
axios.defaults.baseURL = dsktConstant.API_URL;  // 默认地址
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 路由请求拦截
// http request 拦截器
axios.interceptors.request.use(
  config => {
    //判断是否存在ticket，如果存在的话，则每个http header都加上ticket
    if (cookie.get("token")) {
      //用户每次操作，都将cookie设置成2小时
      cookie.set("token", cookie.get("token"), 1 / 12)
      config.headers.common['Authorization'] = cookie.get("token");
    }
    if (config.method == 'post') {
      if (config.data)
        config.data.schoolId = cookie.get("schoolId");
      else
        config.data = { schoolId: cookie.get("schoolId") };
    } else if (config.method == 'get') {
      if (config.params)
        config.params.schoolId = cookie.get("schoolId");
      else
        config.params = { schoolId: cookie.get("schoolId") };
    }
    return config;
  },
  error => {
    alert("请求失败");
    return Promise.reject(error.response);
  });

// 路由响应拦截
// http response 拦截器
axios.interceptors.response.use(
  response => {
    console.log(response.data);
    if (response.data.resultCode == "404") {
      console.log("response.data.resultCode是404")
      // 返回 错误代码-1 清除ticket信息并跳转到登录页面
      //      cookie.del("ticket")
      //      window.location.href='http://login.com'
      return
    } else {
      return response;
    }
  },
  error => {
    if(error.response){
      var ret = error.response.data;
      
      switch (error.response.status) {
        case 401:
          // 错误
          AlertModule.show({
            title: '提示',
            content: "请重新登录"
          });
          //    location.href = "/";
          break;
        default:
          var isInPath = false;
          try{
            if (error.response.data.path){
              for (let i = 0; i < dsktConstant.HTTP_NO_DEAL.length; i++) {
                const path = dsktConstant.HTTP_NO_DEAL[i];
                if (path == error.response.data.path){
                  isInPath=true;
                }
                
              }
            }
          }catch(eee){

          }
          if (!isInPath){
          // 错误
            AlertModule.show({
              title: '提示',
              content: ret.message.substring(0, 30)
            });
          }
          break;
      }
  }
    return Promise.reject(error.response)   // 返回接口返回的错误信息
  });
export default axios;